package com.game.primitive.context;

import com.game.common.QueueEventThread;
import com.game.config.primitive.PrimitiveConfig;
import com.game.config.primitive.RoomConfig;
import com.game.config.primitive.RoomConfig.RoomCfgBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by lizhiwei on 2016/7/6.
 */
@Component
public class PrimitiveLoop extends Thread {
	private Logger logger = LoggerFactory.getLogger(PrimitiveConfig.class);
	private static int frameRate = 0;
	@Autowired
	ApplicationContext applicationContext;
	private Map<Integer, Room> allRoomMap = new ConcurrentHashMap<>();

	@Autowired
	protected QueueEventThread queueEventThread;

	@Override
	public void run() {
		init();
		while (true) {
			long startFlushTime = System.currentTimeMillis();
			queueEventThread.addProcessorTask(() -> {
				for (Room room : allRoomMap.values()) {
					room.loop(System.currentTimeMillis());
				}
				return false;
			});
			long endFlushTime = System.currentTimeMillis();
			long cha = frameRate - (endFlushTime - startFlushTime);
			//如果本次刷帧没有用够一帧的时间，则休息到时间够
			if (cha > 0) {
				try {
					logger.error("刷帧休息" + cha + "秒");
					Thread.sleep(cha);
				} catch (InterruptedException e) {
					logger.error("刷帧休息出错", e);
				}
			} else {
				logger.error("刷帧时间过长" + cha + "秒");
			}
		}

	}

	public void removeRoom(int roomId) {
		allRoomMap.remove(roomId);
	}

	public void addRoom(int roomCfgId) {
		RoomCfgBean roomCfgBean = RoomConfig.getInstance().getRoomCfgBean(roomCfgId);
		if (roomCfgBean == null) {
			logger.error(String.format("%s roomCfgId 没有对应的roomCfgBean模型，请检查", roomCfgId), new Exception("没有对应的roomCfgBean模型"));
			return;
		}
		//Room room = applicationContext.getBean(Room.class);
		Room room = new Room();
		room.setRoomCfgBean(roomCfgBean);
		room.setId(IdGen.getId());
		allRoomMap.put(room.getId(), room);
	}

	public void init() {
		frameRate = 1000 / PrimitiveConfig.getInstance().getFrameRate();
		List<RoomCfgBean> roomList = RoomConfig.getInstance().getRoomCfgBeanList();
		for (RoomCfgBean roomCfgBean : roomList) {
			//Room room = applicationContext.getBean(Room.class);
			Room room = new Room();
			room.setRoomCfgBean(roomCfgBean);
			room.setId(IdGen.getId());
			allRoomMap.put(room.getId(), room);
		}
	}
}
